﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using System;
using System.ComponentModel;
using System.Linq;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 检查运输路线的唯一性
    /// <author>鹿奔</author>
    /// <date>240117</date>
    /// </summary>
    [HotUpdate, Description("保存前检查运输路线的唯一性操作服务插件（挂载到运输路线）")]
    public class EnsureRouteUniquenessOperationServicePlugin : AbstractOperationServicePlugIn
    {
        /// <summary>
        /// 起运点
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_start_point = new ElementKeySchema
        {
            FormKey = "F_RDLV_start_point",
            DbKey = "F_RDLV_START_POINT",
            OrmKey = "F_RDLV_start_point"
        };

        /// <summary>
        /// 运输区域
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_Destion = new ElementKeySchema
        {
            FormKey = "F_RDLV_Destion",
            DbKey = "F_RDLV_DESTION",
            OrmKey = "F_RDLV_Destion"
        };

        /// <summary>
        /// 是否默认路线
        /// </summary>
        internal readonly ElementKeySchema F_RDLV_Default = new ElementKeySchema
        {
            FormKey = "F_RDLV_Default",
            DbKey = "F_RDLV_DEFAULT",
            OrmKey = "F_RDLV_Default"
        };

        /// <summary>
        /// 销售主体
        /// </summary>
        internal readonly ElementKeySchema F_QLTK_salebody = new ElementKeySchema
        {
            FormKey = "F_QLTK_salebody",
            DbKey = "F_QLTK_SALEBODY",
            OrmKey = "F_QLTK_salebody"
        };

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            e.FieldKeys.Add(F_RDLV_start_point.FormKey);
            e.FieldKeys.Add(F_RDLV_Destion.FormKey);
            e.FieldKeys.Add(F_RDLV_Default.FormKey);
        }

        public override void BeforeDoSaveExecute(BeforeDoSaveExecuteEventArgs e)
        {
            base.BeforeDoSaveExecute(e);

            var formData = e.DataEntities.FirstOrDefault();
            if (formData == null)
            {
                throw new KDBusinessException(null, "未能获取到有效的表单数据");
            }

            var billId = Convert.ToInt32(formData["Id"]);
            var startValue = (formData[F_RDLV_start_point.OrmKey] as DynamicObject)?["Id"];
            var endValue = (formData[F_RDLV_Destion.OrmKey] as DynamicObject)?["Id"];
            var saleBody = (formData[F_QLTK_salebody.OrmKey] as DynamicObject)?["Id"]??"0";
            var sql = $@"select top 1 1
                from RDLV_t_TransfRute
                where F_RDLV_DEFAULT = '1'
                    and F_RDLV_START_POINT = @start and F_RDLV_DESTION = @end
                    and isnull(F_QLTK_SALEBODY,'0') = @sale_body
                    and FID != {billId};";
            //var p = new List<SqlParam>
            var p = new SqlParam[]
            {
                new SqlParam("@start", KDDbType.Int32, startValue),
                new SqlParam("@end", KDDbType.Int32, endValue),
                new SqlParam("@sale_body", KDDbType.Int32, saleBody)
            };
            var v = DBUtils.ExecuteScalar(Context, sql, 0, paramList: p);
            var isDefault = formData[F_RDLV_Default.OrmKey] as bool? ?? true;
            if (v == 1 && isDefault)
            {
                throw new KDBusinessException(null, "该起运点已存在其它路线作为默认路线，不允许将该路线设置为默认路线！");
            }
        }
    }
}
